#!/bin/bash

#clean province folder
rm province/*
rm before_cat/*
rm tmp/*

# Seperate data by Province
#sort yiyuan.csv -k 2,5 -t ',' > tmp/done.csv
#./province.out tmp/done.csv
./province.out yiyuan.csv



#sort file by province,city,
for filename in province/*
do
	sort -t "," $filename > tmp/wmj
	cp tmp/wmj $filename
done


# Transform the data in every province to before_cat/
for filename in province/* 
do
	./transform.out $filename
done



# cat all file into yiyuan.js
if [ -f yiyuan.js ]
then
	rm yiyuan.js
fi

printf "var regions={\n" >> yiyuan.js
printf "'请选择地区':{'detail':{'geoInfo':[102.945221,30.180224,6]}},\n" >> yiyuan.js

declare -i num=0

./sort.sh
declare -a sequence 
sequence=$(cat sorted)
#cat ${sequence[*]}

#cat priority province
for city in ${sequence[*]}
do
	for file in before_cat/*
	do
		if [ "${city}".csv = ${file##before_cat/} ]
		then
			if [ $num -ne 0 ]
			then
				printf ",\n" >> yiyuan.js
			fi
			((num+=1))

			cat $file >> yiyuan.js
		fi
	done
done

#cat other province
declare -i flag=0
for catfile in before_cat/*
do
	flag=0
	for city in ${sequence[*]}
	do
		if [ "${city}".csv = ${catfile##before_cat/} ]
		then
			flag=1
		fi
	done

	if [ $flag -eq 0 ]
	then
		if [ $num -ne 0 ]
		then
			printf ",\n" >> yiyuan.js
		fi
		((num+=1))

		cat $catfile >> yiyuan.js
	fi
done

printf "}\n" >>yiyuan.js


sed -nr "H; $ {x; s///g; p}" yiyuan.js | \
sed -nr "H; $ {x; s/\n//g; p}"  > /tmp/wmj_yiyuan
cp /tmp/wmj_yiyuan dizhen-yiyuan.js

# Write to yiyuan.json
sed "s/var regions=\(.*\)$/[\1]/" dizhen-yiyuan.js > dizhen-yiyuan.json
